#include "logger.h"
#include <thread>
#include <time.h>
#include <iostream>

Logger &Logger::getInstance()
{
    static Logger logger;
    return logger;
}
void Logger::setLogLevel(LogLevel logLevel)
{
    logLevel_ = logLevel;
}
void Logger::log(std::string msg)
{
    lockQue_.push(msg);
}

Logger::Logger()
{
    std::thread t([&]
                  {
        while (true)
        {
            time_t now = time(nullptr);
            tm* nowtm = localtime(&now);

            char file_name[128] = {0};
            sprintf(file_name, "%d-%d-%d.log", nowtm->tm_year+1900, nowtm->tm_mon+1, nowtm->tm_mday);

            FILE* fp = fopen(file_name, "a+");
            if(fp == nullptr) {
                std::cout << "open file : " << file_name << "error!" << std::endl;
            }

            std::string msg = lockQue_.pop();


            char time_buf[128] = {0};
            sprintf(time_buf, "%d:%d:%d =>[%s] ", nowtm->tm_hour, nowtm->tm_min, nowtm->tm_sec, (logLevel_ == INFO ? "info" : "error"));

            msg.insert(0, time_buf);

            msg += '\n';

            fputs(msg.c_str(), fp);
            fclose(fp);
        } });
    t.detach();
}